<template>
  <div class="parentDiv">
    <div class="childrenDiv">
      <div class="firstDiv">
        <img src="../../../public/public/image/卓越班LOGO.png" alt=""/>
      </div>
      <div class="secondDiv">
        <div style="float: right; margin: 2%">
          <el-tooltip effect="dark" content="切换主题" v-if="!userstore.isDark">
            <el-button
              @click="toggleDark"
              circle
              style="background-color: var(--login-background3); border: none"
              class="animated clipRectIn"
            >
              <el-icon size="20">
                <Sunny />
              </el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="切换主题" v-if="userstore.isDark">
            <el-button
              @click="toggleDark"
              circle
              style="background-color: var(--login-background3); border: none"
              class="animated clipRectIn"
            >
              <el-icon size="20">
                <Moon />
              </el-icon>
            </el-button>
          </el-tooltip>
        </div>
        <el-form
          ref="loginRuleFormRef"
          style="max-width: 600px"
          :model="loginInfo"
          status-icon
          :rules="loginRules"
          label-width="auto"
          class="demo-ruleForm"
        >
          <h2 style="text-align: center; font-family: 楷体,serif; margin-bottom: 20px; font-size: 24px">
            卓越班报名入口
          </h2>
          <el-form-item prop="username">
            <el-icon style="margin: 0 5px">
              <User />
            </el-icon>
            <el-input
              class="input"
              v-model="loginInfo.username"
              type="text"
              style="width: 80%"
              autocomplete="off"
              placeholder="请输入学号"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-icon style="margin: 0 5px">
              <Lock />
            </el-icon>
            <el-input
              class="input"
              v-model="loginInfo.password"
              type="password"
              style="width: 80%"
              autocomplete="off"
              placeholder="请输入密码"
            />
          </el-form-item>
          <el-form-item>
            <div style="margin-left: -3%; text-align: center; width: 100%">
              <el-button
                style="width: 80%; border-radius: 20px"
                type="primary"
                :loading="loading"
                @click="doLogin"
              >
                登录
              </el-button>
            </div>
            <div
              style="
                text-align: center;
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <span style="font-size: 12px">还没有账号？</span>
              <el-button
                size="small"
                color="white"
                type="text"
                @click="dialogRegisterVisible = true"
              >注册
              </el-button>

              <span style="margin-left: 10%; font-size: 12px">密码忘了？</span>
              <el-button size="small" color="white" type="text" @click="dialogResetVisible = true"
              >重置
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!--    注册信息对话框-->
    <el-dialog v-model="dialogRegisterVisible" title="信息注册" width="450px" append-to-body>
      <el-form :model="Info" ref="registerRuleFormRef" :rules="registerRules" label-width="80px">
        <el-form-item class="el-form-item-one" prop="username" label="学号">
          <el-input style="max-width: 300px" v-model="Info.username" autocomplete="off" />
        </el-form-item>
        <el-form-item class="el-form-item-one" prop="email" label="邮箱">
          <el-input style="max-width: 300px" v-model="Info.email" autocomplete="off" />
        </el-form-item>
        <el-form-item class="el-form-item-one" prop="password" label="密码">
          <el-input
            style="max-width: 300px"
            type="password"
            :show-password="true"
            v-model="Info.password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input
            style="max-width: 300px"
            type="password"
            :show-password="true"
            v-model="Info.confirmPassword"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="code" label="验证码">
          <el-input style="max-width: 150px" v-model="Info.code" autocomplete="off" />
          <el-button style="margin: auto 3%" @click="doSendMsg" :disabled="disabled"
          >{{ time }}
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button type="primary" @click="doRegister">注册</el-button>
          <el-button type="info" @click="cacel">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!--    密码重置-->
    <el-dialog v-model="dialogResetVisible" title="密码重置" width="450px" append-to-body>
      <el-form :model="Info" ref="resetRuleFormRef" :rules="registerRules" label-width="80px">
        <el-form-item prop="username" label="学号">
          <el-input style="max-width: 300px" v-model="Info.username" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input style="max-width: 300px" v-model="Info.email" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input
            style="max-width: 300px"
            type="password"
            :show-password="true"
            v-model="Info.password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input
            style="max-width: 300px"
            type="password"
            :show-password="true"
            v-model="Info.confirmPassword"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="code" label="验证码">
          <el-input style="max-width: 150px" v-model="Info.code" autocomplete="off" />
          <el-button style="margin: auto 3%" @click="doSendMsg" :disabled="disabled"
          >{{ time }}
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button type="primary" @click="doReset">重置</el-button>
          <el-button type="info" @click="dialogResetVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
// import '@/assets/canvas-nest.min.js'
import { onMounted, ref } from 'vue'
import { login, register, resetPassword } from '@/apis/security/user'
import 'element-plus/es/components/message/style/css'
import type { FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import Router from '@/router'
import { checkCode, checkEmail, checkPassword, checkUsername } from '@/utils/checkRule'
import { sendCode } from '@/apis/security/email'
import { userStore } from '@/stores/user'
import { Lock, Moon, Sunny, User } from '@element-plus/icons-vue'

const userstore = userStore()
// 登录按钮加载
const loading = ref(false)

const dialogRegisterVisible = ref(false)
const dialogResetVisible = ref(false)

const loginInfo = ref({
  username: '',
  password: ''
})

// 注册与密码重置数据
const Info = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  code: ''
})

const Code = ref({
  email: ''
})

onMounted(() => {
  changeDark()
})
const toggleDark = () => {
  userstore.isDark = !userstore.isDark
  changeDark()
}
const changeDark = () => {
  const html = document.querySelector('html')
  if (html) {
    if (userstore.isDark) {
      html.classList.remove('light')
      html.classList.add('dark')
    } else {
      html.classList.remove('dark')
      html.classList.add('light')
    }
  }
}

// 校验确认密码
const checkPasswordTow = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value != Info.value.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const cacel = () => {
  dialogRegisterVisible.value = false
  // 数据重置
  Info.value = {
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    code: ''
  }
}

// 登录验证规则
const loginRules = ref<FormRules<typeof loginInfo>>({
  username: [{ validator: checkUsername, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }]
})

// 注册验证规则
const registerRules = ref<FormRules<typeof Info>>({
  username: [{ validator: checkUsername, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }],
  confirmPassword: [{ validator: checkPasswordTow, trigger: 'blur' }],
  email: [{ validator: checkEmail, trigger: 'blur' }],
  code: [{ validator: checkCode, trigger: 'blur' }]
})

const loginRuleFormRef = ref()
const registerRuleFormRef = ref()
const resetRuleFormRef = ref()

// 登录
const doLogin = () => {
  loginRuleFormRef.value.validate((valid: any) => {
    console.log(valid)
    if (valid) {
      loading.value = true
      login(loginInfo.value).then((res) => {
        if (res.data.code === 200) {
          loading.value = false
          userstore.roleList = res.data.data
          userstore.myMenuList = []
          if (userstore.myMenuList.length == 0) {
            if (userstore.roleList.includes('user')) {
              userstore.myMenuList.push(
                { id: 1, name: '首页', path: '/index', icon: 'House' },
                { id: 2, name: '个人信息', path: '/PersonalForms', icon: 'Position' },
                { id: 3, name: '预约考试', path: '/Exam/BookExam', icon: 'EditPen' },
                { id: 4, name: '预约面试', path: '/Interview/BookInterview', icon: 'Clock' },
                { id: 5, name: '班级分组', path: '/Group/GroupSelect', icon: 'Coordinate' },
                { id: 6, name: '我的班级', path: '/Class/Classinfo', icon: 'User' },
                { id: 7, name: '我的小组', path: '/Group/Groups', icon: 'UserFilled' },
              )
            }
            if (userstore.roleList.includes('admin')) {
              userstore.myMenuList.push(
                { id: 8, name: '账号管理', path: '/UserManager', icon: 'User' },
                { id: 9, name: '时间管理', path: '/timeManager', icon: 'Setting' },
                { id: 10, name: '考试管理', path: '/Exam/ExamManager', icon: 'EditPen' },
                { id: 11, name: '面试管理', path: '/Interview/InterviewManager', icon: 'Clock' },
                { id: 12, name: '班级管理', path: '/Class/ClassinfoManager', icon: 'OfficeBuilding' },
                { id: 13, name: '班级成员管理', path: '/Class/ClassMembersManager', icon: 'Place' },
                { id: 14, name: '小组管理', path: '/Group/GroupsManager', icon: 'User' },
                { id: 15, name: '小组成员管理', path: '/Group/GroupMembersManager', icon: 'IceCream' },
                { id: 16, name: '系统设置', path: '/Config/ConfigManager', icon: 'Tools' },
              )
            }
          }
          userstore.userInfo.studentId = loginInfo.value.username
          console.log('登录成功!')
          loginInfo.value = {
            username: '',
            password: ''
          }
          ElMessage({ type: 'success', message: '登录成功' })
          Router.replace('/index')
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
          loading.value = false
        }
      })
    } else {
      console.log('登录失败!')
      loading.value = false
      return false
    }
  })
}

// 注册
const doRegister = () => {
  registerRuleFormRef.value.validate((valid: any) => {
    if (valid) {
      register(Info.value).then((res) => {
        if (res.data.code === 200) {
          // 数据重置
          Info.value = {
            username: '',
            email: '',
            password: '',
            confirmPassword: '',
            code: ''
          }
          dialogRegisterVisible.value = false
          ElMessage({ type: 'success', message: '注册成功' })
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    } else {
      return false
    }
  })
}

// 密码重置
const doReset = () => {
  resetRuleFormRef.value.validate((valid: any) => {
    console.log(valid)
    if (valid === true) {
      resetPassword(Info.value).then((res) => {
        if (res.data.code === 200) {
          // 数据重置
          Info.value = {
            username: '',
            email: '',
            password: '',
            confirmPassword: '',
            code: ''
          }
          dialogResetVisible.value = false
          ElMessage({ type: 'success', message: '密码重置成功' })
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    } else {
      return false
    }
  })
}

// 验证码按钮
const time = ref('发送邮箱验证码')
const wait = ref(60)
const disabled = ref(false)
const doSendMsg = () => {
  if (Info.value.email === '') {
    ElMessage({ type: 'error', message: '请先填写邮箱' })
    return
  }
  Info.value.code = ''
  Code.value.email = Info.value.email
  sendCode(Code.value).then((res) => {
    if (res.data.code === 200) {
      ElMessage({ type: 'success', message: '邮箱验证码发送成功，请注意查收' })
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
  setTime()
}

const setTime = () => {
  if (wait.value == 0) {
    time.value = '发送验证码'
    disabled.value = false
    wait.value = 60
  } else {
    disabled.value = true
    time.value = wait.value + ' 秒'
    wait.value--
    setTimeout(function() {
      setTime()
    }, 1000)
  }
}
</script>

<style lang="scss">
.parentDiv {
  //position: relative;
  position: absolute;
  width: 100%;
  height: 100%;
  min-width: 1200px;
  min-height: 620px;
  max-width: 3000px;
  max-height: 2000px;
  background: url('../../../public/public/image/bg.jpg') no-repeat center center;
  background-size: cover;
}

.childrenDiv {
  z-index: 2;
  display: flex;
  height: 60%;
  max-height: 400px;
  width: 60%;
  min-width: 400px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.firstDiv {
  height: 100%;
  width: 45%;
  background: var(--login-background2);
  border-radius: 20px 0px 0px 20px;

  img {
    width: 70%;
    position: relative;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}

.secondDiv {
  border-radius: 0px 20px 20px 0px;
  height: 100%;
  width: 55%;
  background-color: var(--login-background3);
}

.demo-ruleForm {
  width: 70%;
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.el-input {
  width: 80%;
}
</style>
